import os
from typing import Annotated
from uuid import uuid4

from fastapi import APIRouter, HTTPException, Form, Depends, UploadFile, File
from sqlalchemy.orm import Session
from starlette.responses import JSONResponse
from starlette.routing import Router

import models
from auth import get_current_active_user
from db import get_db, SessionLocal
from user.user_post import storage_path

router = APIRouter(prefix="/api/product", tags=["产品"])


@router.put("/update/{product_id}")
async def update_product(current_user: Annotated[models.User, Depends(get_current_active_user)],product_id: int, name: str = None, price: int = None, description: str = None, image: UploadFile = File(None), db: Session = Depends(get_db)):
    product = db.query(models.Product).filter(models.Product.id == product_id).first()
    if not product:
        raise HTTPException(status_code=404, detail="Product not found")
    if name:
        product.name = name
    if price:
        product.price = price
    if description:
        product.description = description
    if image:
        unique_id = uuid4()
        file_extension = os.path.splitext(image.filename)[1]
        unique_filename = f"{unique_id}{file_extension}"
        file_path = os.path.join(storage_path, unique_filename)
        with open(file_path, "wb") as buffer:
            buffer.write(await image.read())
        new_image_path = f"product/{unique_filename}"
        product.image = new_image_path
    db.commit()
    db.refresh(product)
    return product

